<?php

App::uses('CrudController', 'Controller');

class TestSchedulerController extends CrudController
{
    public $_model = 'Schedule';
    
    public function beforeRender() {
        parent::beforeRender();
        $this->set('kendoTheme', 'kendo.silver');
        
    }
    
    public function admin() {
        $this->request->allowMethod('get');
        $appBosch = new stdClass();
        $appBosch->owner = $this->Auth->user('id');
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Agendar cursos'));
        $this->set('description', 'Planificación de cursos');
    }

    /**
     * Otiene todos las salas disponibles para el Agendar cursos
     */
    public function getRooms()
    {
        $this->loadModel('Room');
        $result = $this->Room->getEnabled();
        $this->set(array('records' => $result, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }
    
    protected function getRecords($param) {
        $m = $this->_model;
        $records = $this->$m->getByOwner($this->Auth->user('id'));
        return $records;
    }

    protected function c($model) {
        $this->loadModel('Room');
        $this->loadModel('Test');
        $room = $this->Room->findById($model->room_id);
        $test = $this->Test->getTestDescriptionById($model->test_id);
        $start = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $model->start);
        $end = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $model->end);
        $this->Session->write('typeService', $model->type);
        return array(
            'test_id' => $model->test_id,
            'user_id' => $model->user_id,
            'start_timezone' => null,
            'start' => $start->format('Y-m-d H:i:s'),
            'end' => $end->format('Y-m-d H:i:s'),
            'end_timezone' => null,
            'recurrence_rule' => null,
            'recurrence_id' => null,
            'recurrence_exception' => null,
            'is_all_day' => $model->is_all_day,
            'room_id' => $model->room_id,
            'room_capacity' => $room['Room']['capacity'],
            'title' => $test['Test']['text'],
            'description' => $test['Test']['text'] . ' en ' . $room['Room']['name'],
            'color' => $test[0]['color']
        );
    }

    protected function afterCreate(&$newRecord)
    {
        $start = DateTime::createFromFormat('Y-m-d H:i:s', $newRecord['start']);
        $end = DateTime::createFromFormat('Y-m-d H:i:s', $newRecord['end']);
        $newRecord['start'] = $start->format('Y-m-d\TH:i:s.u\Z');
        $newRecord['end'] = $end->format('Y-m-d\TH:i:s.u\Z');

        $m = $this->_model;
        $this->loadModel('LogSchedule');
        $this->loadModel($m);
        $reg = $this->$m->findById($newRecord['id']);
        $this->LogSchedule->addCreateLog($this->Auth->user('id'), $reg[$m]);

        $this->loadModel('Test');
        $this->loadModel('TransportRequest');
        $test = $this->Test->findById($newRecord['test_id']);
        $tr = array(
            'user_id' => $this->Auth->user('id'),
            'schedule_id' => $newRecord['id'],
            'motive' => $test['Test']['name'],
            'service_date' => $start->format('Y-m-d H:i:s'),
            'type' => $this->Session->read('typeService')
        );
        $this->Session->delete('typeService');
        $this->TransportRequest->save($tr);
    }

    protected function u($model) {
        $this->loadModel('Room');
        $this->loadModel('Test');
        $room = $this->Room->findById($model->room_id);
        $test = $this->Test->getTestDescriptionById($model->test_id);
        $start = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $model->start);
        $end = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $model->end);
        return array(
            'test_id' => $model->test_id,
            'user_id' => $model->user_id,
            'start_timezone' => null,
            'start' => $start->format('Y-m-d H:i:s'),
            'end' => $end->format('Y-m-d H:i:s'),
            'end_timezone' => null,
            'recurrence_rule' => null,
            'recurrence_id' => null,
            'recurrence_exception' => null,
            'is_all_day' => $model->is_all_day,
            'room_id' => $model->room_id,
            'title' => $test['Test']['text'],
            'description' => $test['Test']['text'] . ' en ' . $room['Room']['name'],
            'color' => $test[0]['color']
        );
    }

    protected function beforeUpdate($id, &$updatedModel)
    {
        $this->loadModel('UserTest');
        $cant = $this->UserTest->getUsCountEnabledByTest($id);
        if ($cant[0]['cant'] != '0') {
            $res = false;
        } else {
            $res = true;
        }

        return $res;
    }

    protected function afterUpdate($id, &$newRecord)
    {
        $start = DateTime::createFromFormat('Y-m-d H:i:s', $newRecord['start']);
        $end = DateTime::createFromFormat('Y-m-d H:i:s', $newRecord['end']);
        $newRecord['start'] = $start->format('Y-m-d\TH:i:s.u\Z');
        $newRecord['end'] = $end->format('Y-m-d\TH:i:s.u\Z');

        $m = $this->_model;
        $this->loadModel('LogSchedule');
        $this->loadModel($m);
        $reg = $this->$m->findById($id);
        $this->LogSchedule->addUpdateLog($this->Auth->user('id'), $reg[$m]);
    }
    
    protected function id($model) {
        return $model->id;
    }

    public function regLogDestroy($id) {
        $comment = $this->request->query('comment');
        $m = $this->_model;
        $this->loadModel($m);
        $this->loadModel('LogSchedule');
        $reg = $this->$m->findById($id);
        $this->LogSchedule->addDestroyLog($this->Auth->user('id'), $reg[$m], $comment);
        $this->generateNotification($id, 3, $comment);
        $this->set(array('records' => true, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    protected function beforeDestroy($id) {
        $this->loadModel('GlobalConfig');
        $hours = $this->GlobalConfig->findByName('training_limit_hours');
        $hours = intval($hours['GlobalConfig']['value']);
        $m = $this->_model;
        $this->loadModel($m);
        $reg = $this->$m->findById($id);
        $now = new DateTime();
        $ds = new DateTime($reg[$m]['start']);
        $diff = date_diff($ds, $now);
        //if ($now->getTimestamp() < $ds->getTimestamp() && $diff->h > $hours) {
            $reg[$m]['closed'] = 1;
            $this->$m->save($reg);
            $resp = $reg[$m];
        /*} else {
            $resp = false;
        }*/

        return $resp;
    }

    public function cancelSchedule() {
        $this->loadModel('GlobalConfig');
        $this->loadModel('UserTest');
        $hours = $this->GlobalConfig->findByName('training_limit_hours');
        $hours = intval($hours['GlobalConfig']['value']);
        $idSche = $this->request->query('id');
        $m = $this->_model;
        $this->loadModel($m);
        $this->$m->id = $idSche;
        $reg = $this->$m->read();
        $now = new DateTime();
        $ds = new DateTime($reg[$m]['start']);
        $diff = date_diff($ds, $now);
        $utTot = $this->UserTest->getUsCountEnabledByTest($idSche);
        $utCalif = $this->UserTest->getUsCountCalifEnabledByTest($idSche);
        $resp = new stdClass();
        if(intval($utCalif[0]['cant']) == 0 || $utCalif[0]['cant'] == $utTot[0]['cant']) {
            //if ($now->getTimestamp() < $ds->getTimestamp() && $diff->h > $hours) {
                $reg[$m]['closed'] = 1;
                $this->$m->save($reg);
                $resp->res = $reg[$m];
            /*} else {
                $resp->res = __('Ya no es posible cancelar el curso porque faltan menos de ') . $hours . __(' horas.');
            }*/
        } else {
            $resp->res = __('No se puede cerrar el curso mientras haya asociados sin calificar');
        }
        $this->set(array('records' => $resp, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    public function regLogCancel($id) {
        $comment = $this->request->query('comment');
        $m = $this->_model;
        $this->loadModel($m);
        $this->loadModel('LogSchedule');
        $reg = $this->$m->findById($id);
        $this->LogSchedule->addCloseLog($this->Auth->user('id'), $reg[$m], $comment);
        $this->generateNotification($id, 4, $comment);
        $this->set(array('records' => true, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    private function generateNotification($idSchedule, $type, $comment = '') {
        $this->loadModel('Notification');
        $this->loadModel('UserTest');
        $usrs = $this->UserTest->getUsIdEnabledByTest($idSchedule);
        $nots = array();
        foreach ($usrs as $u) {
            $nots[] = array(
                'user_id' => $u['userId'],
                'message' => $comment,
                'type' => $type,
                'source_id' => $idSchedule
            );
        }
        $this->Notification->saveMany($nots);
    }
}